package com.why.provider;

import com.why.enums.ErrorEnum;
import com.why.exception.RpcException;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class DefaultServiceRegistry implements ServiceRegistry {
    private static final Map<String, Object> SERVICE_MAP=new ConcurrentHashMap<>();
    private static final Set<String> SERVICE_SET = ConcurrentHashMap.newKeySet();
    /**
     * 完成服务的注册.
     * @param object
     */
    @Override
    public void toRegisterServices(Object object) {
        //如果已经注册该服务了,那就不必再注册一遍
        String name = object.getClass().getCanonicalName();
        if(SERVICE_SET.contains(name)){
            log.warn("这个服务已经被注册了,请不要重复注册!!!");
            return;
        }
        SERVICE_SET.add(name);
        log.info("开始注册服务...");
        //遍历注册的服务的所有接口, 接口名字作为 key,当前类作为value
        Class<?>[] interfaces = object.getClass().getInterfaces();
        for (Class<?> anInterface : interfaces) {
            SERVICE_MAP.put(anInterface.getCanonicalName(),object);
        }

        log.info("注册完毕!当前map集合中的数据为{}",SERVICE_MAP);


    }

    /**
     * 根据服务的名字获取服务
     * @param serviceName
     * @return
     */
    @Override
    public Object getRegisterService(String serviceName) {
       if(!SERVICE_MAP.containsKey(serviceName)){
           log.warn("抱歉,这个接口没有指定的实现类....");
           throw new RpcException(ErrorEnum.NOT_FOUND);
       }

       return SERVICE_MAP.get(serviceName);
    }
}